import { NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { createUser, getUserByUsername, getUserByEmail } from '@/lib/database'
import { validateUserForm, sanitizeUserData } from '@/lib/validation'
import { logSecurityEvent } from '@/lib/rls-middleware'

/**
 * 用户注册 API
 * POST /api/auth/register
 */
export async function POST(request) {
    try {
        const body = await request.json()

        // 验证请求数据
        const validation = validateUserForm(body)
        if (!validation.isValid) {
            return NextResponse.json({
                success: false,
                message: '表单数据验证失败',
                errors: validation.errors
            }, { status: 400 })
        }

        // 检查用户名是否已存在
        const existingUserByUsername = await getUserByUsername(body.username, null) // 注册时不需要用户上下文
        if (existingUserByUsername) {
            return NextResponse.json({
                success: false,
                message: '用户名已存在，请选择其他用户名'
            }, { status: 409 })
        }

        // 检查邮箱是否已存在
        const existingUserByEmail = await getUserByEmail(body.email, null) // 注册时不需要用户上下文
        if (existingUserByEmail) {
            return NextResponse.json({
                success: false,
                message: '邮箱已被注册，请使用其他邮箱或直接登录'
            }, { status: 409 })
        }

        // 加密密码
        const saltRounds = 12
        const passwordHash = await bcrypt.hash(body.password, saltRounds)

        // 准备用户数据
        const userData = {
            username: body.username.trim(),
            email: body.email.trim().toLowerCase(),
            password_hash: passwordHash,
            full_name: body.full_name.trim(),
            application_reason: body.application_reason.trim()
        }

        // 添加可选字段
        if (body.organization?.trim()) {
            userData.organization = body.organization.trim()
        }

        if (body.department?.trim()) {
            userData.department = body.department.trim()
        }

        if (body.phone?.trim()) {
            userData.phone = body.phone.trim()
        }

        // 创建用户
        const newUser = await createUser(userData, null) // 注册时不需要用户上下文

        // 记录注册成功事件
        await logSecurityEvent(newUser.id, 'register_success', 'users', newUser.id, true)

        // 返回成功响应（不包含密码哈希）
        const { password_hash, ...userResponse } = newUser

        return NextResponse.json({
            success: true,
            message: '注册成功',
            user: userResponse
        }, { status: 201 })

    } catch (error) {
        console.error('Registration error:', error)

        // 处理数据库约束错误
        if (error.code === '23505') { // PostgreSQL unique constraint violation
            if (error.constraint?.includes('username')) {
                return NextResponse.json({
                    success: false,
                    message: '用户名已存在'
                }, { status: 409 })
            }
            if (error.constraint?.includes('email')) {
                return NextResponse.json({
                    success: false,
                    message: '邮箱已被注册'
                }, { status: 409 })
            }
        }

        return NextResponse.json({
            success: false,
            message: '注册失败，请稍后重试'
        }, { status: 500 })
    }
}